<template>
  <div class="one">
    <div><p><label about='inStr'>请把mybatis的sql日志粘贴到这里:</label></p>
      <p><textarea v-model='inValue' name='inStr' rows='25' cols='150'></textarea></p>
      <p>
        <button @click="commitFn" style="width:80px;height:40px">解析</button>
        <button @click="clear" style="width:80px;height:40px">清除</button>
      </p>
    </div>

    <div>
      <div v-for='(item,index) in outValue' :key="index" style='border-bottom:2px solid black;padding: 5px; padding-top: 2px'>
        <span class="copy-btn" v-clipboard:copy="item" v-clipboard:success="onCopy" v-clipboard:error="onError">复制</span>
        <pre >{{item}}</pre>
      </div>

    </div>

  </div>
</template>

<script>

import sqlFormatter from 'sql-formatter'

export default {
  name: 'Home',
  components: {
  },
  data: function () {
    return {
      inValue: '',
      outValue: []
    }
  },
  methods: {
    commitFn: function () {
      this.outValue = this.parse(this.inValue)
    },
    clear () {
      this.inValue = ''
      this.outValue = []
    },
    // 复制成功时的回调函数
    onCopy (e) {
      this.$my_message('内容已复制到剪切板！', 'success')
    },
    // 复制失败时的回调函数
    onError (e) {
      this.$my_message('抱歉，复制失败！', 'error')
    },
    copyText (obj) {
    },
    parse (inValue) {
      let split = inValue.split('\n')
      let sb = ''
      let list = []
      if (split && split.length > 0) {
        for (let s of split) {
          if (!s || s.trim().length === 0) continue
          if (s.indexOf('==>  Preparing:') > 0) {
            s = s.substring(s.indexOf('==>  Preparing:') + 15)
            sb = s
            console.log('1:', sb)
          }
          if (s.indexOf('==> Parameters:') > 0) {
            s = s.substring(s.indexOf('==> Parameters:') + 15)
            if (sb.length === 0) continue
            let params = s.split(',')
            console.log(params)
            for (let p of params) {
              p = p.trim()
              if (!p || p === '') continue
              let value = p.substring(0, p.indexOf('('))
              let type = p.substring(p.indexOf('(') + 1, p.indexOf(')'))
              console.log(value, type)
              if ((type.toLowerCase()) === 'string' || (type.toLowerCase()) === 'timestamp') {
                sb = sb.replace(/\?/, '\'' + value + '\'')
              } else {
                sb = sb.replace(/\?/, value)
              }
            }

            let res = sqlFormatter.format(sb.toString())

            list.push(res)
            sb = ''
          }
        }
      }
      return list
    }
  }
}
</script>

<style scoped>
.copy-btn {
  display: inline-block;
  border: 1px solid #42b983;
  color: blue;
  cursor: pointer;
}
</style>
